package com.carlinfo.hospital.controller;

import com.alibaba.fastjson.JSONObject;
import com.carlinfo.hospital.dao.impl.Doctor_personDaoImpl;
import com.carlinfo.hospital.pojo.*;
import com.carlinfo.hospital.service.OrderService;
import com.carlinfo.hospital.service.impl.*;
import com.carlinfo.hospital.util.DataSourceUtil;
import com.carlinfo.hospital.util.DateUtil;
import com.carlinfo.hospital.util.PageInfoUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HelloController
{
    @Autowired
    Doctor_personDaoImpl doctor_personDao;
    @Autowired
    private PersonServiceImpl personService;
    @Autowired
    private Doctor_typeServiceImpl doctor_typeService;
    @Autowired
    private DoctorServiceImpl doctorService;
    @Autowired
    private Doctor_personServiceImpl doctor_personService;
    @Autowired
    private Medicine_TypeServiceImpl medicine_typeService;
    @Autowired
    private MedicineServiceImpl medicineService;
    @Resource(name = "orderServiceImpl")
    private OrderService orderService;

    @RequestMapping("/doctor_type")
    public void doctor_type(HttpServletRequest request, HttpServletResponse response) throws IOException
    {

        response.setContentType("application/json;charset=utf-8");
        System.out.println("=====");
        String id = request.getParameter("id");
        System.out.println(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("typeId", id);
        List<Doctor> doctors = this.doctorService.selectListDao(null, map);
        System.out.println(doctors);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", doctors);

//        String jsonString = JSON.toJSONString(doctors);
        response.getWriter().print(jsonObject);

    }


    @RequestMapping("/")
    public String index()
    {
        return "index";
    }

    @RequestMapping("/xuanyaoSub")
    public void xuanyaoSub(HttpServletRequest request,HttpServletResponse response) throws IOException
    {
        response.setContentType("application/json;charset=utf-8");
        String res = request.getParameter("res");
        String list = request.getParameter("list");
        System.out.println("====="+res);
        System.out.println("========"+list);
        HttpSession session = request.getSession();
        String id = (String) session.getAttribute("userId");
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",id);
        Person person = personService.selectOnePersonService(map);
        person.setContent(person.getContent()+res);
        int i = personService.updateOnePersonService(person);
        JSONObject jsonObject = new JSONObject();
        Doctor doctor = (Doctor) session.getAttribute("doctor");

        int money = 0;
        String[] split = list.split(",");
        for (int j = 0; j <split.length-1 ; j++)
        {
            Map<String,Object> condMap = new HashMap<String,Object>();
            condMap.put("id",split[j]);
            Order order = orderService.selectOneDao(condMap);
            money+=order.getMoney();
        }
        if(i>0)
        {
            Order order = new Order();
            order.setPersonId(Integer.valueOf(id));
            DateUtil dateUtil = new DateUtil();
            order.setCreateTime(new Date());
            order.setPublicTime(new Date());
            order.setContent("无");
            order.setStatus(0);
            order.setMoney(money);
            order.setUpdateTime(new Date());
            orderService.saveOneDao(order);
            jsonObject.put("info","提交成功!");
        }else
        {
            jsonObject.put("info","提交失败!");
        }
        response.getWriter().print(jsonObject);
    }



    @RequestMapping("/guahao")
    public String guahao(Model model)
    {
        //doc_type
        Map<String, Object> map = new HashMap<>();
        List<Doctor_type> doc_type = doctor_typeService.selectListDao(null, map);
        model.addAttribute("doc_type", doc_type);
        return "guahao";
    }


    @RequestMapping("/userList")
    public String userList(Model model)
    {
        Map<String, Object> map = new HashMap<>();
        List<Person> personList = personService.selectListPersonService(null, map);
        model.addAttribute("list",personList);
        return "userList";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model) throws SQLException
    {
        Map<String, Object> map = new HashMap<>();
        List<Person> personList = personService.selectListPersonService(null, map);
        String identity = request.getParameter("identity");
        if (identity.equalsIgnoreCase("1"))
        {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String sql  ="select * from nurse where username=? and password=?";
            Nurse nurse = new QueryRunner(DataSourceUtil.getInstance()).query(sql,new BeanHandler<Nurse>(Nurse.class),username,password);
            if(nurse!=null)
            {
                model.addAttribute("list", personList);
                return "main";
            }else
            {
                return "index";
            }
        }
        if (identity.equalsIgnoreCase("2"))
        {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            Map<String, Object> condMap = new HashMap<String, Object>();
            condMap.put("username", username);
            condMap.put("password", password);
            //医生登录查询
            Doctor doctor = doctorService.selectOneDao(condMap);

            if (doctor != null)
            {
                //查询这个医生需要治疗病人的总数量
                String pageSize = request.getParameter("pageSize");
                String currentPage = request.getParameter("currentPage");
                Map<String, Object> map1 = new HashMap<String, Object>();
                PageInfoUtil pageInfoUtil = new PageInfoUtil();
                long count = new QueryRunner(DataSourceUtil.getInstance()).query("select count(*) from doctor_person where doctorId = ?", new ScalarHandler<>(), doctor.getId());
                pageInfoUtil.setTotalRecord(Integer.valueOf(count + ""));
                if (pageSize != "" && pageSize != null)
                {
                    pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
                }
                if (currentPage != "" && currentPage != null)
                {
                    pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
                }
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("doctorId", doctor.getId());
                List<Person> personList1 = personService.selectListPersonService(pageInfoUtil, map2);
                model.addAttribute("list", personList1);
                System.out.println(personList1);
                model.addAttribute("pageInfoUtil", pageInfoUtil);
                model.addAttribute("doctor",doctor);
                HttpSession session = request.getSession();
                session.setAttribute("doctor",doctor);
                return "doctor_login";
            } else
            {
                return "index";
            }
        }
        return "index";
    }

    @RequestMapping("kaiyao")
    public String kaiyao(HttpServletRequest request, Model model) throws Exception
    {
        String id = request.getParameter("personId");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        Person person = personService.selectOnePersonService(map);
        String content = request.getParameter("content");
        person.setContent(content);
        this.personService.updateOnePersonService(person);
        String pageSize = request.getParameter("pageSize");
        String currentPage = request.getParameter("currentPage");
        Map<String, Object> map1 = new HashMap<String, Object>();
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        long count = new QueryRunner(DataSourceUtil.getInstance()).query("select count(*) from medicine_type", new ScalarHandler<>());
        pageInfoUtil.setTotalRecord(Integer.valueOf(count + ""));
        if (pageSize != "" && pageSize != null)
        {
            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
        }
        if (currentPage != "" && currentPage != null)
        {
            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
        }
        List<Medicine_type> medicine_types = medicine_typeService.selectListDao(pageInfoUtil, map1);
        model.addAttribute("list", medicine_types);
        model.addAttribute("pageInfoUtil", pageInfoUtil);
        model.addAttribute("personId",person.getId());
        model.addAttribute("personId",id);
        model.addAttribute("content",content);
        return "repayment_list";
    }

    @RequestMapping("xuanyao")
    public String xuanyao(HttpServletRequest request,Model model) throws Exception
    {
        String personId = request.getParameter("personId");
        String id = request.getParameter("doctorId");
        Map<String ,Object> conMap = new HashMap<String, Object>();
        conMap.put("typeId",id);
        String pageSize = request.getParameter("pageSize");
        String currentPage = request.getParameter("currentPage");
        Map<String, Object> map1 = new HashMap<String, Object>();
        PageInfoUtil pageInfoUtil = new PageInfoUtil();
        long count = new QueryRunner(DataSourceUtil.getInstance()).query("select count(*) from medicine where typeId = ?", new ScalarHandler<>(),id);
        pageInfoUtil.setTotalRecord(Integer.valueOf(count + ""));
        if (pageSize != "" && pageSize != null)
        {
            pageInfoUtil.setCurrentPage(Integer.valueOf(currentPage));
        }
        if (currentPage != "" && currentPage != null)
        {
            pageInfoUtil.setPageSize(Integer.valueOf(pageSize));
        }
        List<Medicine> medicines = this.medicineService.selectListDao(pageInfoUtil, conMap);
        model.addAttribute("list", medicines);
        model.addAttribute("pageInfoUtil", pageInfoUtil);
        model.addAttribute("doctorId",id);
        model.addAttribute("personId",personId);
        return "xuanyao";
    }

    @RequestMapping("/guahaoSub")
    public String guahaoSub(HttpServletRequest request, Model model)
    {
        String name = request.getParameter("name");
        String doctorId = request.getParameter("doctor");
        String sex = request.getParameter("sex");
        String identity = request.getParameter("identity");
        Person person = new Person();
        person.setName(name);
        person.setSex(sex);
        person.setIdentity(identity);
        person.setCreateTime(new Date());
        person.setUpdateTime(new Date());
        person.setPublicTime(new Date());
        int id = personService.saveOnePersonService(person);

        /* 存关联关系 */
        Doctor_person doctorPerson = new Doctor_person();
        doctorPerson.setPersonId(id);
        doctorPerson.setDoctorId(Integer.valueOf(doctorId));
        doctorPerson.setCreateTime(new Date());
        doctorPerson.setPublicTime(new Date());
        doctorPerson.setUpdateTime(new Date());
        doctor_personService.saveOneDao(doctorPerson);
        Map<String, Object> map = new HashMap<>();
        List<Person> personList = personService.selectListPersonService(null, map);
        model.addAttribute("list", personList);
        return "main";
    }

    @RequestMapping("/zhenduan")
    public String zhenduan(HttpServletRequest request, Model model)
    {
        String id = request.getParameter("id");
        HttpSession session = request.getSession();
        session.setAttribute("userId",id);
        System.out.println(id);
        Map<String, Object> condMap = new HashMap<String, Object>();
        condMap.put("id", id);
        Person person = this.personService.selectOnePersonService(condMap);
        model.addAttribute("person", person);
        return "card_update";
    }
}
